<template>
  <div class="user_page">
    <div class="user_search">
      <el-input
        v-model="cdtUsername"
        class="filter-item"
        placeholder="账号"
        size="small"
        style="width: 200px"></el-input>
      <el-button class="filter-item" type="primary" icon="el-icon-search" size="small" @click="searchSalon">
        查询
      </el-button>
      <el-button class="filter-item" icon="el-icon-refresh" size="small" @click="resetSalon">重置</el-button>
    </div>

    <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column prop="username" fixed label="账号" align="left" width="120"></el-table-column>
      <el-table-column prop="nickName" fixed label="用户名" align="left" width="150"></el-table-column>
      <el-table-column prop="deptId" label="角色" align="center" :formatter="fmtRole" width="180"></el-table-column>
      <el-table-column prop="consumerNum" label="顾客数" align="center"></el-table-column>
      <el-table-column prop="keeperMoney" label="成交金额" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.keeperMoney > 0 ? row.keeperMoney.toFixed(2) : row.keeperMoney }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="sname" label="所属店铺" align="center" width="400" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width" width="210">
        <template slot-scope="{ row, $index }">
          <el-button v-if="row.isFrozen === 0" plain type="warning" size="mini" @click="frozeUser(row, 1)">
            停用
          </el-button>
          <el-button v-else type="success" plain size="mini" @click="frozeUser(row, 0)">启用</el-button>
          <el-button type="primary" size="mini" plain @click="handleUpdate(row)">编辑</el-button>
          <el-button type="danger" size="mini" plain @click="handleDelete(row.id, $index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="fetchData"></pagination>

    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :model="adminObj" label-width="110px" style="margin-right: 30px" :rules="rules">
        <el-form-item label="账号" prop="username">
          <el-input v-model="adminObj.username" :disabled="isUpdate"></el-input>
        </el-form-item>
        <el-form-item v-show="title == '新增'" label="密码" prop="note">
          <el-input v-model="adminObj.note"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="nickName">
          <el-input v-model="adminObj.nickName"></el-input>
        </el-form-item>
        <el-form-item label="角色" required>
          <el-radio-group v-model="adminObj.deptId">
            <el-radio v-for="item in sysRoles" :label="item.id">{{ item.name }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属店铺" required>
          <span>{{ adminObj.sname }}</span>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updateData()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as apiSts from '@/api/_com_';
// 引入后端 API
import { changeFrozen, delAdmin, editAdmin, getUserPage } from '@/api/admin';
import { countConsumerByKeepers } from '@/api/txs';
import { sumMoneyByKeepers } from '@/api/ym';
// 引入自定义组件
import Pagination from '@/components/Pagination';
import { getRoleName, systemRoles } from '@/utils/enum/roles';
// 引入第三方组件
import dayjs from 'dayjs';
import { mapGetters } from 'vuex';

export default {
  components: { Pagination },
  filters: {
    parseTime(time) {
      return dayjs(time).format('YYYY-MM-DD');
    },
  },
  data() {
    return {
      salonId: undefined,
      lstCountConsumer: [],
      lstSumMoney: [],
      cdtUsername: '',
      cdtSname: '',
      total: 0,
      listQuery: {
        page: 1,
        limit: 10,
      },
      sysRoles: systemRoles.filter(x => x.id > 1),
      dialogFormVisible: false,
      adminObj: {
        id: undefined,
        username: '',
        note: '',
        nickName: '',
        deptId: 203,
        openId: '0',
        sname: '',
      },
      title: '',
      isUpdate: false,
      list: [],
      listSalon: null,
      listLoading: false,
      rules: {
        username: [{ required: true, message: '必填项', trigger: 'blur' }],
        note: [{ required: true, message: '必填项', trigger: 'blur' }],
        nickName: [{ required: true, message: '必填项', trigger: 'blur' }],
      },
    };
  },
  computed: {
    ...mapGetters(['name', 'id', 'openId']),
  },
  created() {
    this.salonId = parseInt(this.openId);
    this.fetchData();
  },
  methods: {
    searchSalon() {
      if (!this.salonId || !Number.isFinite(+this.salonId)) {
        return;
      }
      this.loadUserList();
    },
    resetSalon() {
      if (!this.salonId || !Number.isFinite(+this.salonId)) {
        return;
      }
      this.cdtSname = '';
      this.cdtUsername = '';
      this.loadUserList();
    },
    frozeUser(row, froze) {
      row.isFrozen = froze;
      const dataInfo = new FormData();
      dataInfo.append('froze', froze);
      changeFrozen(row.id, dataInfo);
    },
    clickSalons(val) {
      this.adminObj.sname = val;
    },
    fmtRole(row) {
      const tmp = getRoleName(row.deptId);
      return tmp === undefined ? '' : tmp;
    },
    fetchData() {
      this.loadUserList();
    },
    async statistic(ids) {
      const [resCr, resMy] = await Promise.all([countConsumerByKeepers(ids), sumMoneyByKeepers(ids)]);
      this.lstCountConsumer = resCr.data.data;
      this.lstSumMoney = resMy.data.data;

      this.list.forEach(k => {
        const cr = this.lstCountConsumer.find(c => c.kid === k.id);
        const my = this.lstSumMoney.find(m => m.kid === k.id);
        this.$set(k, 'consumerNum', cr ? cr.ct : 0);
        this.$set(k, 'keeperMoney', my ? my.total : 0);
      });
    },
    loadUserList: async function () {
      if (this.listLoading) {
        return;
      }
      this.listLoading = true;
      const errAlertMsg = '查询用户列表失败';
      const params = { pageNumber: this.listQuery.page, pageSize: this.listQuery.limit };
      if (this.cdtUsername) {
        params.username = this.cdtUsername;
      }
      if (this.cdtSname) {
        params.sname = this.cdtSname;
      }
      if (this.openId) {
        params.sids = '' + this.openId;
      }
      this.list.splice(0, this.list.length);
      await getUserPage(params)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          const ret = res.data.data;
          if (ret) {
            if (ret.records && ret.records.length) {
              this.list.push(...ret.records);
            }
            this.total = ret.total;
          }
          if (this.list && this.list.length) {
            const ids = this.list.map(item => item.id);
            this.statistic(ids);
          }
        })
        .catch(err => {
          console.error(err);
          MessageBox.alert(errAlertMsg);
        })
        .finally(() => (this.listLoading = false));
    },
    handleUpdate(row) {
      this.title = '编辑';
      this.isUpdate = true;
      this.dialogFormVisible = true;
      this.adminObj = Object.assign({}, row);
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate();
      });
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.adminObj);
          editAdmin(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.adminObj.id);
            this.list.splice(index, 1, tempData);
            this.dialogFormVisible = false;
            this.$notify({
              title: 'Success',
              message: '更新成功',
              type: 'success',
              duration: 2000,
            });
          });
        }
      });
    },
    handleDelete(id, index) {
      this.$confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          delAdmin(id).then(() => {
            this.$notify({
              title: 'Success',
              message: '删除成功',
              type: 'success',
              duration: 2000,
            });
          });
          this.list.splice(index, 1);
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
@import '@/assets/css/scrollbar.scss';

.user_page {
  width: 100%;

  .user_search {
    padding: 5px 16px;
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    gap: 5px;
  }
}

::v-deep .el-table td {
  padding: 5px 0;
  min-width: 0;
  box-sizing: border-box;
  text-overflow: ellipsis;
  vertical-align: middle;
  position: relative;
}
</style>
